package com.demo.ruiji.controller;

import com.demo.ruiji.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Value("${uploadFile.path}")
    private String uploadPath;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upLoad(MultipartFile file){//file参数名必须和前端的name属性值一致
        //file是一个临时文件，需要转存到指定位置，否则临时文件会被删掉
        log.info(file.toString());

        //获取文件名
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //防止文件名重复，使用UUID重新生成文件名
        fileName = UUID.randomUUID().toString() + suffix;

        //创建一个目录对象
        File dest = new File(uploadPath);
        //判断目录是否存在，不存在则创建
        if (!dest.exists()){
            dest.mkdirs();
        }

        try {
            //讲临时文件转存到指定的位置
            file.transferTo(new File(uploadPath + fileName));
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){

        try {
            //输入流读取文件
            FileInputStream fileInputStream = new FileInputStream(new File(uploadPath + name));
            //输出,流写回浏览器,在浏览器展示图片
            ServletOutputStream outputStream = response.getOutputStream();

            //设置输出文件类型
            response.setContentType("image/jpeg");

            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
           e.printStackTrace();
        }

    }

}
